/*

release_id:发布的唯一标识id

img_url：发布的图片

header_url：发布人的头像

date：发布日期

title：发布标题

nickname:网名

browse：浏览量

Fabulous：点赞量

username_id:用户的唯一标识

user_unique:存储点赞用户唯一标识数组
*/
/*
comments_posted--发布评论的表

posted_id:评论的id

date：发布日期

nickname:发布人的名字

posted_content：发布内容
*/

const router = require('express').Router()
const mysql = require('../mysql/mysql.js')
var request = require('request');
var fs = require('fs');
var path = require('path');
const formidable = require("formidable");
mysql.open('8.131.83.251', 'root', '123456', 'haoshipu_back', () => {
    console.log('连接失败')
}, () => {
    console.log('连接成功')
})
// 获取时间 date
function formatDate(now) {
    // var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var date = now.getDate();
    // var hour = now.getHours();
    // var minute = now.getMinutes();
    // var second = now.getSeconds();
    // return year + "年" + month + "月" + date + "日" + hour + ":" + minute + ":" + second;
    return month + "月" + date + "日"
}

//图片上传

router.post('/image', (req, res) => {
    let imageList = []
    const form = new formidable.IncomingForm(); //既处理表单，又处理文件上传
    form.uploadDir = path.join(__dirname, "../public/foodfriends") //设置上传的文件存放在哪里
    form.parse(req, function (err, fields, files) {
        if (err) {
            res.json({
                code: 501,
                msg: "上传失败",
                errmsg: err,
            })
        }
        const oldPath = files.image.path // 路径
        // console.log(files.file.name)//图片传过来的名字
        const newPath = path.join(path.dirname(oldPath), files.image.name)
        // const downUrl = 'https://localhost:5656/public/foodfriends/' + files.image.name //这里是想传回图片的链接
        const downUrl = 'https://www.webpti.cn:5656/public/foodfriends/' + files.image.name //这里是想传回图片的链接
        //fs.rename重命名图片名称
        fs.rename(oldPath, newPath, (data) => {
            // console.log("185",data);
        });
        imageList.push(downUrl)
        res.json({ code: 2, imageList })
    })
})

// 发布接口
router.post('/upload', (req, res) => {
    let data = req.body
    let sql = `INSERT INTO release_data SET ?`
    mysql.handleData(sql, data, (response) => {
        console.log(response)
        res.json({ code: 200 })
        mysql.close()
    })
})


// 发布页面数据
router.post('/releasedata', (req, res) => {
    mysql.handleData(`SELECT * FROM release_data ORDER BY release_id DESC`, '', (data) => {
        if (Object.keys(data).length < 0) {
            res.json({ msg: '没有数据' })
            mysql.close()
        } else {
            res.json({ code: 200, data: data })
            mysql.close()
        }
    })
})


//发表评论接口
router.post('/comment', (req, res) => {
    console.log(req.body)
    //如果记得时间戳是毫秒级的就需要*1000 不然就错了记得转换成整型
    let date = formatDate(new Date(Date.parse(new Date())))
    let data = {
        posted_content: req.body.value,
        posted_date: date,
        rele_id: req.body.rele_id,
        avatarUrl: req.body.avatarUrl,
        nick: req.body.nickName
    }
    mysql.handleData(`INSERT INTO comments_posted SET ?`, data, (data) => {
        console.log(data)
        res.json({ code: 200 })
        mysql.close()
    })
})

// 获取评论数据
router.get('/pinglun', (req, res) => {
    if (!req.query) {
        res.json({ code: 400, msg: '没有传参数' })
    } else {
        mysql.handleData(`SELECT * FROM pinglun_view WHERE release_id='${req.query.detailsID}'  ORDER BY posted_id DESC `, '', async (response) => {
            await res.json({ code: 200, response: response })
            mysql.close()
        })
    }
})


// 食友说列表详情页的点赞接口
router.get('/releasedetails', (req, res) => {
    // console.log(req.query)
    if (!req.query) {
        res.json({ code: false, msg: '没有传参数' })
    } else {
        mysql.handleData(`SELECT browse,Fabulous FROM release_data WHERE release_id='${req.query.detailsID}' `, '', async (response) => {
            await res.json({ code: 200, num: response })
            mysql.close()
        })
    }
})


// 获取轮播图和用户标题数据
router.get('/userdetails', (req, res) => {
    if (!req.query) {
        res.json({ code: 400, msg: '没有传参数' })
    } else {
        mysql.handleData(`SELECT img_url,header_url,date,title,nickname FROM release_data WHERE release_id='${req.query.detailsID}' `, '', async (response) => {
            res.json({ code: 200, data: response })
            mysql.close()
        })
    }
})

// 点赞接口
router.get('/dianzan', (req, res) => {
    // 查询语句
    let sql = `SELECT * FROM release_data WHERE release_id='${Number(req.query.id)}'`
    mysql.handleData(sql, '', (data) => {
        let arr = JSON.parse(data[0].user_unique) // 存储标识数组
        // 如果arr是null就创建一个新的数组
        if (arr === null) {
            arr = new Array()
        }
        let browse = data[0].browse // 点赞量
        let index = arr.findIndex(item => item === req.query.signature) // 返回下标 返回-1 说明没有找到，不是
        if (index < 0) {
            //如果数组中没有这个标识，那就添加进去，然后并加一
            arr.push(req.query.signature)
            ++browse
            // 更新语句
            let updateSql = `UPDATE release_data SET ? WHERE release_id='${Number(req.query.id)}'`
            mysql.handleData(updateSql, {
                user_unique: JSON.stringify(arr),
                browse: browse
            }, data => {
                console.log(data)
                res.json({ code: 200, msg: '点赞成功' })
                // 关闭数据库
                mysql.close()
            })
        } else {
            arr.splice(index, 1)
            --browse
            let updateSql = `UPDATE release_data SET ? WHERE release_id='${Number(req.query.id)}'`
            mysql.handleData(updateSql, {
                user_unique: JSON.stringify(arr),
                browse: browse
            }, data => {
                console.log(data)
                res.json({ code: 200, msg: '取消点赞' })
                // 关闭数据库
                mysql.close()
            })
        }
    })
})


// 浏览接口
router.get('/liulan', (req, res) => {
    mysql.handleData(`SELECT * FROM release_data WHERE release_id='${Number(req.query.id)}'`, '', response => {
        if (response) {
            let reult = response.find(item => item.Fabulous)
            if (reult) {
                mysql.handleData(`UPDATE release_data SET ? WHERE release_id='${Number(req.query.id)}'`, {
                    Fabulous: Number(reult.Fabulous) + 1
                }, resData => {
                    res.json({ code: 200, msg: '浏览成功' })
                })
            } else {
                res.json({ code: false, msg: '浏览失败' })
            }
        } else {
            res.json({ code: 500, msg: '没有这个页面' })
        }
    })
})


module.exports = router
